﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace LEV_Applications
{
    public class ClientSocket : IDisposable
    {
        private TcpClient tcpClient;
        private NetworkStream networkStream;

        public ClientSocket()
        {
        }
        ~ClientSocket()
        {
        }
        //Implement IDisposable.
        public void Dispose()
        {
            //Dispose(true);
            //GC.SuppressFinalize(this);
        }
        public void Connect(string host, int port)
        {
            tcpClient = new TcpClient();
            tcpClient.Connect(host, port);
        }

        public bool NetworkStreamStatus()
        {
            bool status = false;

            try
            {
                networkStream = tcpClient.GetStream();

                if (networkStream.CanRead && networkStream.CanWrite)
                {
                    status = true;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                status = false;
            }
            return status;
        }

        public void SendMessageString(string strMessage)
        {
            try
            {
                NetworkStream ns = tcpClient.GetStream();
                Byte[] sendBytes = Encoding.UTF8.GetBytes(strMessage);
                ns.Write(sendBytes, 0, sendBytes.Length);
            }
            catch (Exception ex)
            {
            }
        }

        public void SendMessageByteArray(byte[] byteMessage)
        {
            networkStream.Write(byteMessage, 0, byteMessage.Length);
        }

        public byte[] ReceiveMessageByteArray(ref int byteSize)
        {
            networkStream = tcpClient.GetStream();
            byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
            byteSize = networkStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);

            return bytes;
        }

        public void CloseConnection()
        {
            if (networkStream != null)
            {
                networkStream.Close();
            }
            tcpClient.Close();
        }

    }//public class ClientSocket
}//namespace LEV_Applications
